package com.nowcoder.community.controller;

import com.nowcoder.community.entity.Event;
import com.nowcoder.community.event.EventProducer;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

@Controller
public class ShareController implements CommunityConstant {
    //前端一访问就生成图片，生成图片时间较长，所以一定是异步的方式，
    // controller只需把事件丢给卡夫卡，后续用卡夫卡异步实现，而不是在这儿等着
    private static final Logger logger = LoggerFactory.getLogger(ShareController.class);
    @Autowired
    private EventProducer eventProducer;//因为要用卡夫卡
    @Value("${community.path.domain}")
    private String domain;//应用程序域名
    @Value("${server.servlet.context-path}")
    private String contextPath;//项目访问名
    @Value("${wk.image.storage}")
    private String wkImageStorage;//图片存放位置

    @RequestMapping(path = "/share",method = RequestMethod.GET)
    @ResponseBody//异步
    public String share(String htmlUrl){
        // 文件名（随机，每次都要变，不然很容易重名）
        String fileName = CommunityUtil.generateUUID();

        //异步生成长图
        Event event = new Event()
                .setTopic(TOPIC_SHARE)
                .setData("htmlUrl", htmlUrl)
                .setData("fileName", fileName)
                .setData("suffix", ".png");
        eventProducer.fireEvent(event);

        // 生成长图以后，如何访问呢---返回访问路径
        Map<String ,Object> map = new HashMap<>();
        //domain项目域名
        map.put("shareUrl", domain + contextPath + "/share/image/" + fileName);

        return CommunityUtil.getJSONString(0, null, map);
    }

    //获取长图
    @RequestMapping(path = "/share/image/{fileName}",method = RequestMethod.GET)
    public void getShareImage(@PathVariable("fileName") String fileName, HttpServletResponse response) {

        if (StringUtils.isBlank(fileName)) {//参数为空，抛出异常
            throw new IllegalArgumentException("文件名不能为空!");
        }

        response.setContentType("image/png");//image表示输出的图片，png表示输出的格式
        File file = new File(wkImageStorage + "/" + fileName + ".png");//实例化file
        try {
            OutputStream os = response.getOutputStream();
            FileInputStream fis = new FileInputStream(file);//把文件转为输入流
            byte[] buffer = new byte[1024];//缓冲区
            int b = 0;//游标
            while ((b = fis.read(buffer)) != -1) {//!= -1表示读到了数据
                os.write(buffer, 0, b);
            }
        } catch (IOException e) {
            logger.error("获取长图失败: " + e.getMessage());
        }
    }
}
